package cn.zcltd.btg.set.servlet;

import cn.zcltd.btg.set.util.ServletUtil;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * btgset页面支持及json api入口
 */
public class BtgSetServlet extends HttpServlet {
    protected final String resourcePath = "cn/usbtg/plugin/set/web";

    @Override
    public void init() throws ServletException {
        String classPath = this.getClass().getResource("/").getPath();
        PropertyConfigurator.configure(classPath + "/debug.log4j.properties");
    }

    protected String getFilePath(String fileName) {
        return resourcePath + fileName;
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");

        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String requestURI = request.getRequestURI();

        //System.out.println(contextPath);
        //System.out.println(servletPath);
        //System.out.println(requestURI);

        contextPath = contextPath == null ? "" : contextPath;

        String uri = contextPath + servletPath;
        String path = requestURI.substring(contextPath.length() + servletPath.length());

        //System.out.println(uri);
        //System.out.println(path);

        returnResourceFile(path, uri, response);
    }

    protected void returnResourceFile(String fileName, String uri, HttpServletResponse response) throws IOException {
        String filePath = getFilePath(fileName);

        //System.out.println(filePath);

        if (filePath.endsWith(".html")) {
            response.setContentType("text/html; charset=utf-8");
        }

        if (fileName.endsWith(".jpg")) {
            byte[] bytes = ServletUtil.readByteArrayFromResource(filePath);
            if (bytes != null) {
                response.getOutputStream().write(bytes);
            }
            return;
        }

        String text = ServletUtil.readFromResource(filePath);

        //System.out.println(text);

        if (text == null) {
            response.sendRedirect(uri + "/index.html");
            return;
        }

        if (fileName.endsWith(".css")) {
            response.setContentType("text/css;charset=utf-8");
        }
        if (fileName.endsWith(".js")) {
            response.setContentType("text/javascript;charset=utf-8");
        }

        response.getWriter().write(text);
    }
}